package com.googlecode.connectlet.web;

import java.io.File;

import org.eclipse.jetty.deploy.WebAppDeployer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;

public class Jetty {
	public static Server createServer(File home) throws Exception {
		return createServer(home, 80);
	}

	public static Server createServer(File home, int port) throws Exception {
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);
		Server server = new Server();
		server.addConnector(connector);
		initWebApp(server, home);
		return server;
	}

	public static Server createServer(File home, File filePfx, String password) throws Exception {
		return createServer(home, 443, filePfx, password);
	}

	public static Server createServer(File home, int nPort, File filePfx, String password) throws Exception {
		SslSelectChannelConnector connector = new SslSelectChannelConnector();
		connector.setPassword(password);
		connector.setKeystoreType("PKCS12");
		connector.setKeystore(filePfx.getPath());
		connector.setKeyPassword(password);
		connector.setTruststoreType("PKCS12");
		connector.setTruststore(filePfx.getPath());
		connector.setTrustPassword(password);
		connector.setWantClientAuth(true);
		connector.setPort(nPort);
		Server server = new Server();
		server.addConnector(connector);
		initWebApp(server, home);
		return server;
	}

	private static void initWebApp(Server server, File home) throws Exception {
		HandlerCollection handler = new HandlerCollection();
		server.setHandler(handler);
		WebAppDeployer webapp = new WebAppDeployer();
		webapp.setContexts(handler);
		webapp.setWebAppDir(home + File.separator + "webapps");
		webapp.start();
	}
}